package com.questetra.bpms.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.questetra.bpms.android.Preferences.NotFoundException;

public class SettingsActivity extends Activity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        Button button = (Button) findViewById(R.id.ButtonOk);
        button.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        Spinner spinner = (Spinner) findViewById(R.id.EditUrl);
        String[] hosts = getResources().getStringArray(R.array.settings_urls);
        EditText path = (EditText) findViewById(R.id.EditPath);
        EditText consumerKey = (EditText) findViewById(R.id.EditOAuthConsumerKey);
        EditText consumerSecret = (EditText) findViewById(R.id.EditOAuthConsumerSecret);
        try {
            QbpmsInfo info = Preferences.getQbpmsInfo(this);
            for (int i = 0; i < hosts.length; i++) {
                if (hosts[i].equals(info.host)) {
                    spinner.setSelection(i);
                }
            }
            path.setText(info.path);
            consumerKey.setText(info.consumerKey);
            consumerSecret.setText(info.consumerSecret);
        } catch (NotFoundException e) {
            consumerKey.setText(OAuthService.CONSUMER_KEY);
        }
    }

    public void onClick(View view) {
        QbpmsInfo info = new QbpmsInfo();

        Spinner spinner = (Spinner) findViewById(R.id.EditUrl);
        EditText edit = (EditText) findViewById(R.id.EditPath);
        info.host = spinner.getSelectedItem().toString();
        info.path = edit.getText().toString();
        edit = (EditText) findViewById(R.id.EditOAuthConsumerSecret);
        info.consumerSecret = edit.getText().toString().trim();

        OAuthService.getInstance().reset(this, info);
        
        Intent intent = new Intent(getApplicationContext(),
                                   WorkitemListActivity.class);
        startActivity(intent);
        finish();
    }
}
